package sort;

import java.util.Arrays;

public class MergeSort {  // 归并排序 O(N * logN)  空间O(N)
    public static void main(String[] args) {
        int[] array = {27,15,19,28,68,6};
        int[] array1 = {27,15,19,28,68,6};
        mergeSort(array);
        mergeSort1(array1);
        System.out.println(Arrays.toString(array));
        System.out.println(Arrays.toString(array1));
    }
    public static void mergeSort(int[] array){  // 递归实现
        merge(array,0,array.length-1);
    }
    public static void merge(int[] array, int left, int right){  // 分解
        if(left >= right){
            return;
        }
        int mid = (left + right) / 2;
        merge(array, left, mid);
        merge(array, mid + 1, right);
        mergeAnd(array, left, right, mid);
    }
    public static void mergeAnd(int[] array, int start, int end, int mid){  // 合并
        int[] temp = new int[end - start + 1];
        int k = 0;
        int s1 = start;
        int s2 = mid + 1;
        while (s1 <= mid && s2 <= end){
            if(array[s1] < array[s2]){
                temp[k++] = array[s1++];
            } else {
                temp[k++] = array[s2++];
            }
        }
        while (s1 <= mid){
            temp[k++] = array[s1++];
        }
        while (s2 <= end){
            temp[k++] = array[s2++];
        }
        for (int i = 0; i < temp.length; i++) {
            array[i+start] = temp[i];
        }
    }
    public static void mergeSort1(int[] array) {  // 非递归实现
        int gap = 1;
        while (gap < array.length){
            for (int i = 0; i < array.length; i += 2 * gap) {
                int left = i;
                int mid = left + gap - 1;
                if(mid >= array.length){
                    mid = array.length - 1;
                }
                int right = mid + gap;
                if (right >= array.length){
                    right = array.length - 1;
                }
                mergeAnd(array,left, right, mid);
            }
            gap *= 2;
        }
    }
}
